<?php
	// check params size and names
	if (sizeof($_GET) != 4 || !array_key_exists('id', $_GET) || !array_key_exists('key', $_GET) || !array_key_exists('hun', $_GET) || !array_key_exists('code', $_GET))
	{
		echo "Usage";
		exit;
	}

	// if passed then connect to db and define vars
	$mysqli = new mysqli('localhost', 'root', 'project3', 'implauth');
	if ($mysqli->connect_errno)
	{
		echo "db caoonection error!";
		exit;
	}
	$id = $_GET['id'];
	$key = $_GET['key'];
	$hun = $_GET['hun'];
	$code = $_GET['code'];

	// if passed then validate id and key
	$res = $mysqli->query("select count(*) as total from servers where id like '$id' and secretkey like '$key'");
	$ob = $res->fetch_object();
	$res->close();
	if ($ob->total != 1)
	{
		echo "id/key not exist";
		$mysqli->close();
		exit;
	}

	// if passed then check for code collision
	$res = $mysqli->query("select count(*) as total from accountstbr where code like '$code'");
	$ob = $res->fetch_object();
	$res->close();
	if ($ob->total != 0)
	{
		echo 1;
		$mysqli->close();
		exit;
	}

	// if passed then try to update first
	$res = $mysqli->query("update accountstbr set code = '$code' where serverid like '$id' and hun like '$hun'");
	if ($mysqli->affected_rows != 0)
	{
		echo 0;
		$mysqli->close();
		exit;
	}

	// if passed then try to insert
	$res = $mysqli->query("insert into accountstbr values ('$id', '$code' , '$hun')");
	if (!$res)
	{
		echo 2;
		$mysqli->close();
		exit;
	}
	$mysqli->close();
	echo 0;
	


























	

?>
